#import "LCPageLoadMonitor.h"

@implementation LCPageLoadMonitor {
    CFRunLoopObserverRef _observer;
}

static CFAbsoluteTime lastTime = 0;

+ (instancetype)sharedInstance {
    static LCPageLoadMonitor *ins;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        ins = [[self alloc] init];
    });
    return ins;
}

+ (void)startMonitor {
    [[self sharedInstance] start];
}

+ (void)stopMonitor {
    [[self sharedInstance] stop];
}

- (void)start {
    if (_observer) return;

    CFRunLoopObserverContext context = {0, NULL, NULL, NULL, NULL};
    _observer = CFRunLoopObserverCreate(NULL,
                                        kCFRunLoopBeforeSources,
                                        YES, 0,
                                        &runLoopObserverCallback,
                                        &context);
    CFRunLoopAddObserver(CFRunLoopGetMain(), _observer, kCFRunLoopCommonModes);
}

- (void)stop {
    if (_observer) {
        CFRunLoopRemoveObserver(CFRunLoopGetMain(), _observer, kCFRunLoopCommonModes);
        CFRelease(_observer);
        _observer = NULL;
    }
}

static void runLoopObserverCallback(CFRunLoopObserverRef observer, CFRunLoopActivity activity, void *info) {
    CFAbsoluteTime now = CFAbsoluteTimeGetCurrent();
    if (lastTime == 0) {
        lastTime = now;
        return;
    }
    CFTimeInterval diff = now - lastTime;
    if (diff > 0.05) {
        NSLog(@"[LCPageLoadMonitor] 卡顿 %.0f ms", diff * 1000);
    }
    lastTime = now;
}

@end